package net.piggy.core;

import com.alibaba.fastjson.JSONObject;
import net.piggy.domain.MethodBean;
import net.piggy.domain.RequestFuture;
import net.piggy.domain.Response;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Mediator {
    public static Map<String, MethodBean> methodBeans = new HashMap<>();;

    public static Response process(RequestFuture requestFuture){

        String path = requestFuture.getPath();
        Response response = new Response();
        MethodBean methodBean = methodBeans.get(path);
        if(methodBean!=null){
            Object bean = methodBean.getBean();
            Method method = methodBean.getMethod();

            Object[] params = requestFuture.getParam();

            Class<?>[] paramTypes = method.getParameterTypes();
            Object [] objects = new Object[paramTypes.length];
            int i = 0;
            for(Class<?> c: paramTypes){
                Object p = JSONObject.parseObject(JSONObject.toJSONString(params[i]),c);
                objects[i] = p;
                i++;
            }

            try {
                Object myResult = method.invoke(bean,objects);
                response.setResult(myResult);
            } catch (Exception e) {
                response.setResult("function invoke fail");
                e.printStackTrace();
            }

        }else{
            response.setResult("function not exist");
        }
        response.setId(requestFuture.getId());
        return response;
    }


}
